/**
 * 
 * 可通过 $page 获取或修改当前页面的 变量 状态 handler lifecycle 等信息
 * 可通过 app 获取或修改全局应用的 变量 状态 等信息
 * 具体可以console.info 在编辑器Console面板查看更多信息
 * 注意：该方法仅在所属的页面有效
 * 如果需要 async-await，请修改成 export default async function() {}
 **/
/**
 * @param {Object} event - 事件对象.
 * @param {string} event.name - 事件名.
 * @param {string} event.target - 事件的目标节点(触发该事件的节点).
 * @param {string} event.currentTarget - 当前处理该事件的节点。包括冒泡和捕获事件。.
 *
 * @param {Object} data
 * @param {any} data.target - 获取事件传参的数据
 **/
export default async function ({ event, data }) {
  if (app.platform === 'MINIPROGRAME') {
    try {
      const cloud = await app.cloud.getCloudInstance();
      const auth = cloud.auth;
      const { appId: providerId } = wx.getAccountInfoSync().miniProgram;
      const endpointType = app.__internal__ && app.__internal__.getCloudSdkConfig && app.__internal__.getCloudSdkConfig('endpointType');
      const isTcbApi = endpointType === 'tcb-api';
      const phoneCode = event.detail.code
      const providerInfo = {};
      if (isTcbApi) {
        const { code } = await wx.login();
        providerInfo.provider_id = providerId;
        providerInfo.provider_code = code;
      } else {
        const tokenRes = await app.cloud.callWedaApi({
          action: 'GetMiniProgramUserTicket',
          data: {
            Type: `externalUser`,
            EncryptedPhoneData: phoneCode,
          },
        });
        const token = tokenRes?.token || tokenRes;
        if (!token) {
          throw new Error('invalid empty mp user ticket');
        }
        providerInfo.provider_id = 'weda';
        providerInfo.provider_access_token = `${
          app.utils._getConfig
            ? app.utils._getConfig().envId
            : app.__internal__ && app.__internal__.getConfig && app.__internal__.getConfig().envId
        } ${token}`;
      }
      
      let providerToken = await auth.grantProviderToken(providerInfo);
      if (providerToken.code) {
        throw providerToken;
      }
      if (isTcbApi) {
        providerToken = await auth.patchProviderToken({
          provider_token: providerToken.provider_token,
          provider_id: providerId,
          provider_params: {
            code: phoneCode
          },
        })
      }
      const signInRes = await auth.signInWithProvider({
        provider_token: providerToken.provider_token,
      });
      if (signInRes.code) {
        throw signInRes;
      }
      await app.cloud.signIn({ userType: 'externalUser', force: true });
      $page.handler.loginSuccessCallBack();
    } catch (e) {
      console.error('登录失败：', e);
      app.showModal({
        title: '登录失败',
        content: e.errMsg || e.message || JSON.stringify(e),
        showCancel: false,
      })
      throw e;
    }
  }
}